package com.candy.biz.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.candy.biz.domain.param.SysDictItemQueryParam;
import com.candy.biz.domain.param.SysDictItemSaveParam;
import com.candy.biz.domain.vo.DictSelectItemVO;
import com.candy.biz.domain.vo.SysDictItemVO;
import com.candy.biz.manager.SysDictManager;
import com.candy.common.enums.RedisKeyEnum;
import com.candy.common.manager.RedisManager;
import com.mybatisflex.core.query.If;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.candy.biz.domain.entity.SysDictItem;
import com.candy.biz.mapper.SysDictItemMapper;
import com.candy.biz.service.SysDictItemService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.candy.biz.domain.entity.table.SysDictItemTableDef.SYS_DICT_ITEM;

/**
 * 字典项 服务层实现。
 *
 * @author rong xi
 * @since 1.0.0
 */
@Service
public class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper, SysDictItem> implements SysDictItemService {

    /**
     * 分页查询字典项
     * @param param 分页参数
     * @return 分页结果
     */
    @Override
    public List<SysDictItemVO> queryList(SysDictItemQueryParam param) {
         List<SysDictItem> list =  queryChain()
                .select(SYS_DICT_ITEM.ALL_COLUMNS)
                .from(SYS_DICT_ITEM)
                .where(SYS_DICT_ITEM.ITEM_NAME.like(param.getDictItemName(), If::hasText))
                .and(SYS_DICT_ITEM.DICT_ID.eq(param.getDictId(), If::notNull))
                .and(SYS_DICT_ITEM.DICT_CODE.eq(param.getDictCode(), If::hasText))
                .orderBy(param.getOrderBy(SYS_DICT_ITEM))
                .list();
            return SysDictManager.itemsToItemVos(list);
    }

    @Override
    public List<DictSelectItemVO> queryDictSelectItem(String dictCode) {
        return SysDictManager.getDictMap(dictCode).entrySet().stream()
                .map(e->DictSelectItemVO.builder().label(e.getKey()).value(e.getValue()).build())
                .collect(Collectors.toList());

    }

    /**
     * 保存字典项
     * @param param 字典项参数
     * @return 保存结果
     */
    @Override
    @Transactional
    public Boolean saveHandle(SysDictItemSaveParam param) {
        //删除旧数据
        this.remove(SYS_DICT_ITEM.DICT_ID.eq(param.getDictId()));
        Optional.ofNullable(param.getItems())
                .filter(CollectionUtil::isNotEmpty)
                .map(l->BeanUtil.copyToList(l, SysDictItem.class))
                .ifPresent(pre->{
                    List<SysDictItem> collect = pre.stream().peek(e -> {
                        e.setId(IdUtil.getSnowflakeNextId());
                        e.setDictId(param.getDictId());
                        e.setDictCode(param.getDictCode());
                        e.setCreateTime(LocalDateTime.now());
                        e.setCreateUser(StpUtil.getLoginIdAsLong());
                    }).toList();
                    this.saveBatch(collect);
                });
        RedisManager.delete(RedisKeyEnum.DICT_MAP.getKey(param.getDictCode()));
        return true;
    }

    /**
     * 删除字典项
     * @param id 字典项id
     * @return 删除结果
     */
    @Override
    public Boolean removeHandle(Long id) {
        this.removeById(id);
        return true;
    }

}
